<template>
  <div id="recharge">
    <div class="page-header">
    	<div class="balance">
    		<i class="el-icon-ali-balance"></i>
    		<span class="title">当前账号余额（{{merchantMoneyText}}）：</span>
    		<span class="money">{{merchantCapital}}</span>
    	</div>
    	<div class="freeze-balance">
    		<i class="el-icon-ali-freeze-money"></i>
    		<span class="title">当前冻结余额（{{merchantMoneyText}}）：</span>
    		<span class="money">{{freezeMoney}}</span>
    	</div>
      <div class="freeze-balance">
        <i class="el-icon-ali-freeze-money"></i>
        <span class="title">当前充值金额（{{merchantMoneyText}}）：</span>
        <span class="money">{{recharge_money}}</span>
      </div>
    </div>
    <div class="card">
      <div class="card-header">
        <div class="title">提交充值</div>
      </div>
      <div class="card-content">
          <div class="steps">
            <div class="step-cell">
              <i class="el-icon-ali-bank-info info-icon"></i>
              <span class="name">请先转账到以下账号</span>
            </div>
            <i class="el-icon-ali-arrow-right arrow-right-icon"></i>
            <div class="step-cell">
              <i class="el-icon-ali-edit edit-icon"></i>
              <span class="name">确认提交转账金额</span>
            </div>
          </div>
          <div class="steps-content">
            <div class="box">
              <div class="bank-info-box">
                <div class="bank-name">{{bankInfo.bank_name}}</div>
                <div class="bank-num">{{bankInfo.bank_num}}</div>
                <div class="user-name">户名：{{bankInfo.user_name}}</div>
                <div class="user-name">支行：{{bankInfo.open_bank}}</div>
              </div>
              <div class="note-box">
                <div class="note-header">充值注意事项：</div>
                <div class="note-content" style="color: red">
                  <p>1.充值转账请使用支付宝  商家转账  这个功能（支付宝上方搜索  商家转账），可以减少风控和被封机率!!!</p>
                  <p>2.审核时间：上午8:30~12:00，下午14:00~19:00，因金融新规问题，夜间不再提供充值服务，请提前安排充值，19点后的转账将无法提交，敬请谅解！</p>
                  <p>3.收款账号会不定期更换，需要清晰的转账人姓名、金额、具体时间，请关注页面显示的账号是否变更；</p>
                  <p>4.审核以转款人及单笔到账金额为准，若转账多笔请按笔分别提交，多笔合并一笔会审核失败；</p>
                  <p>5.财务对账、银行处理转账会有延迟情况，审核时间段内超过30分钟未处理的，可联系对接客服发转账截图确认；</p>
                  <p>6.请不要恶意重复提交，以免被人工封号！</p>
                </div>
              </div>
            </div>
            <div class="box">
              <div class="recharge-box">
                <el-form :model="ruleForm" status-icon :rules="rules2" ref="ruleForm" label-width="120px" class="demo-ruleForm">
                  <el-form-item label="转账金额" prop="transferMoney">
                    <el-input v-model="ruleForm.transferMoney" type="number" :clearable="true" placeholder="请输入转账金额" size="small" />{{merchantMoneyText}}
                  </el-form-item>

                  <el-form-item label="转账银行" prop="transferBank">
                    <el-input v-show="this.checked==true" size="small" placeholder="请输入银行" v-model="ruleForm.transferBank"></el-input>
                    <el-select v-show="this.checked==false" v-model="ruleForm.transferBank" placeholder="请选择银行" size="small">
                      <el-option v-for="item in bankOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    <el-checkbox v-model="checked">其他银行</el-checkbox>
                  </el-form-item>
                  <el-form-item label="转账人姓名" prop="transferName" >
                    <el-input v-model.number="ruleForm.transferName" placeholder="请输入转账人姓名" size="small"></el-input>
                  </el-form-item>
                  <el-form-item label="转账截图" prop="transferImg">
                    <el-upload class="avatar-uploader" action="https://upload-z2.qiniup.com" :http-request="sliderRequest" :name="fileName" :data="uploadData"
                      :show-file-list="false" accept=".jpg,.jpeg,.png" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                      <img v-if="ruleForm.transferImg" :src="ruleForm.transferImg" class="avatar">
                      <i v-else class="el-icon-ali-upload avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>
                  <el-form-item>
                    <el-button class="sumbit-btn" style="margin-top: 20px;" :disabled="submitLoading" :loading="submitLoading" @click="submitForm">提交</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
      </div>
    </div>
    <div class="card">
      <div class="card-header">
        <div class="title">充值记录</div>
      </div>
      <div class="card-contetnt">
        <div class="recharge-table-box">
          <el-table :data="tableData" border size="mini" >
            <el-table-column prop="create_time" label="提交时间"></el-table-column>
            <el-table-column prop="transfer_bank" label="转账银行"></el-table-column>
            <el-table-column prop="transfer_name" label="开户名"></el-table-column>
            <el-table-column prop="transfer_money" :label="'金额' + '('+merchantMoneyText+')'"></el-table-column>
            <el-table-column prop="receive_name" label="收款姓名"></el-table-column>
            <el-table-column prop="receive_card_num" label="收款卡号"></el-table-column>
            <el-table-column prop="status" :formatter="getCheckStatus" label="审核状态"></el-table-column>
            <el-table-column prop="check_time" :formatter="changeCheckTimeType" label="审核时间"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
          <el-table :data="allTableData" border size="mini" id="exportTable" v-show="false">
            <el-table-column prop="create_time" label="提交时间"></el-table-column>
            <el-table-column prop="transfer_bank" label="转账银行"></el-table-column>
            <el-table-column prop="transfer_name" label="开户名"></el-table-column>
            <el-table-column prop="transfer_money" label="金额"></el-table-column>
            <el-table-column prop="receive_name" label="收款姓名"></el-table-column>
            <el-table-column prop="receive_card_num" label="收款卡号"></el-table-column>
            <el-table-column prop="status" :formatter="getCheckStatus" label="审核状态"></el-table-column>
            <el-table-column prop="check_time" :formatter="changeCheckTimeType" label="审核时间"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
          <div class="table-footer">
            <el-button icon="el-icon-download" class="download-btn" @click="downloadExcel">导出</el-button>
            <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" :current-page="page" layout="total, sizes, prev, pager, next, jumper"
              :total="pageTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import {
  apiSubmitMerchantRecharge,
  apiMerchantRecharge,
  apiUploadToken
} from '../../request/api.js'
  import axios from 'axios'
  export default {
    data(){
      return {
        tableData: [],
        bankInfo: {},
        checkStatus: {
          1: '审核成功',
          2: "审核失败",
          3: "未审核"
        },
        merchantCapital: 0.00,
        freezeMoney: 0.00,
        recharge_money:0.00,
        submitLoading: false,
        allTableData: [],
        ruleForm: {
          transferMoney: "",
          transferBank: "",
          transferName: "",
          transferImg: '',
          receiveName: '',
          receiveCardNum: ''
        },
        rules2: {
          transferMoney: [
           { required: true, message: '请输入转账金额', trigger: 'blur' }
          ],
          transferBank: [
            { required: true, message: '请输入转账银行', trigger: 'blur' }
          ],
          transferName: [
             { required: true, message: '请填写银行卡姓名', trigger: 'blur' }
          ],
          transferImg: [
             { required: true, message: '请上传转账截图', trigger: 'change' }
          ]
        },
         bankOptions: [{
          value: '中国银行',
          label: '中国银行'
        }, {
          value: '农业银行',
          label: '农业银行'
        }, {
          value: '建设银行',
          label: '建设银行'
        }, {
          value: '工商银行',
          label: '工商银行'
        }, {
          value: '招商银行',
          label: '招商银行'
        }, {
          value: '兴业银行',
          label: '兴业银行'
        }, {
          value: '中国邮政储蓄银行',
          label: '中国邮政储蓄银行'
        }, {
          value: '交通银行',
          label: '交通银行'
        }],
        uploadData: {
          area: 'money'
        },
        imageUrl: '',
        checked: false,
        page:1,
        pageSize:5,
        pageTotal: 0,
        merchantMoneyText:  window.localStorage.getItem("merchantMoneyText"),
        userToken: window.localStorage.getItem('token'),
        uploadToken: '',
        fileName: ''
      }
    },
    created() {
      apiUploadToken({}).then(res =>{
        if(res.code == 1)  {
          this.uploadToken = res.msg
        }
      }).catch(res => {
        this.$message.error(res.msg)
      })
      this.getTableData()
    },
    methods:{
      getTableData() {
        // 获取表格数据
        this.$isClick(true);
        apiMerchantRecharge({
          page: this.page,
          pageSize: this.pageSize,
          token: this.userToken
        }).then(res =>{
          this.$isClick(false);
           if (res.code == 1){
            this.bankInfo =  res.msg.bank_info ? res.msg.bank_info : {}
            this.merchantCapital = res.msg.merchant_capital;
            this.freezeMoney = res.msg.freeze_money;
             this.recharge_money = res.msg.recharge_money;
            this.tableData = res.msg.merchant_recharge_list
            this.pageTotal = res.msg.all_num
           } else {
              this.$message.error(res.msg);
            }
        }).catch(res => {
          this.$isClick(false);
            this.$message.error(res.msg)
        })
      },
      submitForm(){
        if (parseInt(this.ruleForm.transferMoney) == 0) {
          this.$message.error("转账余额不能为0")
          return
        }

        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.ruleForm.transferImg.indexOf('money') < 0 && this.ruleForm.transferImg.indexOf('reCharge') < 0) {
              this.$message.error("请重新上传转账截图")
              return
            }
            this.submitLoading = true
              apiSubmitMerchantRecharge({
                transferMoney: this.ruleForm.transferMoney,
                transferBank: this.ruleForm.transferBank,
                transferName: this.ruleForm.transferName,
                transferImg: this.ruleForm.transferImg,
                token: this.userToken,
                receiveName: this.bankInfo.user_name,
                receiveCardNum: this.bankInfo.bank_num
              }).then(res =>{
                 this.submitLoading = false
                 if (res.code == 1){
                  this.$refs['ruleForm'].resetFields();
                  this.ruleForm.transferBank = ''
                  this.ruleForm.transferImg = ''
                  this.getTableData()
                  return this.$message.success(res.msg);
                 } else {
                    this.$message.error(res.msg);
                  }
              }).catch(res => {
                this.submitLoading = false
                this.$message.error(res.msg)
              })
            } else {
               this.submitLoading = false
            }
        })

      },
      sliderRequest(upload) {
        console.log(upload.file,upload.file.name,this.uploadToken)
        // 文件上传自行处理上传
        // 创建FormData对象 添加相关上传参数
        const formData = new FormData()
        // 文件对象
        formData.append('file', upload.file)
        // key 文件名处理，这样的话七牛会识别文件时什么类型
        const timestamp = new Date().getTime()
        formData.append('key', 'reCharge/' + timestamp +upload.file.name)
        // token
        formData.append('token', this.uploadToken)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
        // 上传文件
        // onUploadProgress 查看axios文档 https://github.com/axios/axios
        let _this = this
        axios.post("https://upload-z2.qiniup.com", formData, {
          onUploadProgress: (event) => {
            // 监听上传进度
            event.percent = event.loaded / event.total * 100
            upload.onProgress(event)
          }
        }).then((response) => {
          const res = response.data
          console.log(res,response.status)
          if (response.status === 200) {
            _this.handleAvatarSuccess(res);
          }
        }).catch((err) => {
          // 调用组件上传失败方法
          console.log(err)
        })
      },
      handleAvatarSuccess(res, file) {
        this.ruleForm.transferImg = this.BASE_QINIU_URL + res.key
        console.log(this.ruleForm)
        this.$message.success('上传成功');
      },
      beforeAvatarUpload(file) {
        this.fileName = file.name;
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
          this.$message.error('上传商品图片大小不能超过 10MB!');
        }
        this.uploadImgStatus = 1
        return isLt2M;
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getTableData();
      },
      handleCurrentChange(val) {
        this.page = val;
        this.getTableData();
      },
      changeCheckTimeType(row) {
       if (row.check_time == 0 || row.check_time == '' || row.check_time == null) {
         return '--'
       }
       if (typeof(row.check_time) != 'number') {
         return row.check_time
       }
       var date = new Date(row.check_time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
       return this.getFormatTime(date)
      },
      getFormatTime(date) {
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' +  date.getDate() : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
        var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
        return Y + M + D + h + m + s;
      },
      getCheckStatus(row) {
        return this.checkStatus[row.status]
      },
      getAllTableData(){
       if (this.pageTotal == 0) {
          this.$message.error('当前表格没有数据可以导出');
          return
       }
        return new Promise ((resolve) =>{
          this.$isClick(true);
          apiMerchantRecharge({
            page: 1,
            pageSize: this.pageTotal,
            token: this.userToken
          }).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
                this.allTableData = res.msg.merchant_recharge_list
               resolve(res) ;
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
        })

      },
      downloadExcel(){
        this.$loading.show('下载中')
        var wb = ''
         var xlsxParam = { raw: true }
         this.getAllTableData().then(()=>{
         wb = this.XLSX.utils.table_to_book(document.querySelector('#exportTable'),xlsxParam)
         var wbout = this.XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
         try {
           this.FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }),'充值记录.xlsx')
         } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
         setTimeout(() => {
           this.$loading.hide()
           this.$message.success('下载完成')
         }, 1000);
         return wbout
        })
      }
    }
  }
</script>

<style lang="less">
  #recharge {
    .page-header {
      background: #FFFFFF;
      padding: 10px 0;
      margin-bottom: 16px;
      box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
      div {
        display: inline-block;
        text-align: center;
        width: 30%;
      }
      .title {
        color: #666666;
        margin: 0 5px;
        font-size: 14px;
      }
      .money {
        color: @themeColor;
        font-size: 18px;
      }
      .balance {
        i {
          color: rgb(251,193,60);
          font-size: 20px;
          vertical-align: middle;
        }
      }
      .freeze-balance {
        i {
          color: red;
          font-size: 20px;
          vertical-align: middle;
        }

      }
    }
    .card {
      background: #FFFFFF;
      margin-bottom: 16px;
      box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
      padding-bottom: 16px;
      border-radius: 5px;
      .card-header {
        background: #ecf5ff;
        padding: 10px;
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        .title {
          line-height: 20px;
          border-left: 3px solid #666666;
          padding-left: 10px;
          font-size: 16px;
          font-weight: 700;
          color: #333333;
          width: 150px;
        }
      }
      .card-content {
        padding: 10px 20px;

        .steps {
          background: #f5f7fa;
          .arrow-right-icon {
            font-size: 22px;
            vertical-align: middle;
            color: #b5b5b5;
          }
          .step-cell {
            padding: 10px 0;
            display: inline-block;
            width: 48%;
            text-align: center;
            .info-icon {
              color: red;
              font-size: 18px;
              vertical-align: middle;
              vertical-align: middle;
              display: inline-block;
              margin-top: -3px;
            }
            .edit-icon {
              color: @themeColor;
              font-size: 18px;
              vertical-align: middle;
              display: inline-block;
              margin-top: -3px;
            }
            .name {
              color: #333333;
              font-size: 14px;
              margin-left: 5px;
            }
          }
        }
        .steps-content {
          .box {
            display: inline-block;
            width: 49%;
            vertical-align: text-top;
            .recharge-box {
              margin: 20px auto;
              padding-left: 15%;
              .el-input--small {
                width: 200px!important;
                margin-right: 10px;
              }
              .avatar-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
              }

              .avatar-uploader .el-upload:hover {
                border-color: #409EFF;
              }

              .avatar-uploader-icon {
                font-size: 22px;
                color: #8c939d;
                width: 130px;
                height: 170px;
                line-height: 170px;
                text-align: center;
              }

              .avatar {
                width: 130px;
                height: 170px;
                display: block;
              }
              .sumbit-btn {
                width: 200px;
                background: @themeColor;
                padding: 10px 0;
                color: #FFFFFF;
              }
            }

            .bank-info-box {
              border: 1px solid #e0e0e0;
              border-radius: 12px;
              box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
              width: 345px;
              // padding: 10px;
              margin: 20px auto;
              background-image: url(../../assets/image/bank_img.png);
              background-size: 100% 100%;
              background-repeat: no-repeat;
              height: 190px;
              .bank-num {
                color: #FFFFFF;
                background: #333333;
                font-size: 15px;
                padding: 6px 20px;
                font-style:oblique;
                font-weight: bold;
                letter-spacing: 2px;
                margin-bottom: 10px;
              }
              .bank-name {
                 color: #FFFFFF;
                 font-size: 18px;
                 font-weight: bold;
                 padding: 10px 20px;
              }
              .user-name {
                color: #FFFFFF;
                font-size: 15px;
                 padding: 6px 20px;
              }
            }
            .note-box {
               border: 1px solid #d7d7d7;
               padding: 10px;
               border-radius: 5px;
               width: 80%;
               margin: 0 auto;
              .note-header {
                font-weight: 700;
                font-size: 14px;
                color: #333;
              }
              .note-content {
                font-size: 12px;
                margin-left: 10px;
                color: #666;
                line-height: 25px;
              }
            }

          }
        }
      }
    }
    .recharge-table-box {
      padding: 10px 30px;
      .el-table thead tr, .el-table thead tr th{
      	background: #f5f7fa!important;
      }
      .el-table td, .el-table th {
      	padding: 9px 0 !important;
      }
      .table-footer {
      	display: flex;
      	align-items: center;
      	justify-content:space-between;
      	margin-top: 10px;
      	.download-btn {
      		height: 35px !important;
      		line-height: 35px;
      		padding: 0px 20px !important;
      		margin-left: 10px;
      		font-size: 14px;
      		color: #409eff;
      		background: #ecf5ff;
      		border-color: #b3d8ff;
      	}
      }
    }
  }
</style>
